package com.mall.web.control.weishang;

import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.mall.biz.pay.PayBizImpl;
import com.mall.common.util.bit.PropertiesConfigure;
import com.mall.constant.PropertiesKey;
import com.mall.pojo.User;
import com.mall.web.util.WebUtil;
import com.tencent.common.Configure;

@Controller
@RequestMapping("/weixin/")
public class WeixinController implements InitializingBean {
	private static final Logger log = LoggerFactory.getLogger(WeixinController.class);
	
	
	@Autowired
	private PayBizImpl payBizImpl;
	
	
	
	
	/**
	 * 鉴权成功后返回页面地址
	 */
	private static String AUTH_RETURN_URI;

	/**
	 * 支付完成异步通知接口地址
	 */
	private static String PAY_NOTIFY_URL;
	

	/**
	 * 鉴权请求地址模板
	 */
	private static final String REDIRECT_URL_TPL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_base&state=%s#wechat_redirect";

	/**
	 * 回调通知处理成功后返回给微信的消息
	 */
	private static final String SUCCESS_MSG = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";

	/**
	 * 获取access_token接口地址
	 */
	private static final String ACCESS_TOKEN_API_URL = "https://api.weixin.qq.com/sns/oauth2/access_token";

	@Autowired
	private PropertiesConfigure propertiesConfigure;
	
	
	
	
	@RequestMapping("auth")
	public String auth(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws Exception {
		log.error("开始授权请求...");
		// 将订单ID先保存在session中，待授权完成后继续取出使用
		log.error("pay>sessionId:{}", request.getSession().getId());
		User user = WebUtil.getCurrentUser(request);
		String state = String.format("%08d", user.getId());// 这里需要加密

		String AUTH_RETURN_URI = PropertiesKey.httpbeginurl+"/weishang/user/index.htm?";

		String redirectUrl = String.format(REDIRECT_URL_TPL, Configure.getAppid(),
				URLEncoder.encode(AUTH_RETURN_URI, "utf-8"), state);
		log.error("redirectTo:{}", redirectUrl);
		return "redirect:" + redirectUrl;
	}




	@Override
	public void afterPropertiesSet() throws Exception {
		// TODO Auto-generated method stub
		
	}
	
}
